import { defineStore } from "pinia";
import cache from '@/utils/cache'

export const userStore = defineStore('userStore', {
    state: () => {
		return {
			// 用户信息
			user: cache.getUserInfo(),
			// 登录token
			token: cache.getToken(),
			// 记住我
			remember: cache.getRemember(),
			// 菜单列表
			menus: cache.getMenu(),
			// 历史菜单查询
			menuSearchRecord: cache.getMenuSearchRecord(),
			// 权限列表
			buttons: cache.getButtons(),
			// 应用小程序
			applets: cache.getApplets(),
			// 任务栏tab页
			tabs: [],
			// 固定Tabs
			affixTabs: cache.getAffixTabs(),
			// 缓存路由
			cacheRoutes: cache.getKeepAliveRoutes(),
		}
	},
    actions: {
        setUser(val: any) {
			this.user = val
			cache.setUserInfo(this.user)
		},
		updateUser(val: any) {
			Object.keys(val).forEach((k: string) => {
				this.user[k] = val[k]
			})
			cache.setUserInfo(this.user)
		},
		setToken(val: any) {
			this.token = val
			cache.setToken(this.token)
		},
		setRemember(val: any) {
			this.remember = val
			cache.setRemember(this.remember)
		},
		setMenu(val: any) {
			this.menus = val;
			cache.setMenu(this.menus)
		},
		changeMenuSearchRecord (value: string | number) {
			if (typeof value === 'number') {
				if (value === -1) {
					this.menuSearchRecord.splice(0);
					cache.deleteMenuSearchRecord();
				} else {
					this.menuSearchRecord.splice(value, 1);
					if (this.menuSearchRecord.length <= 0) {
						cache.deleteMenuSearchRecord();
					} else {
						cache.setMenuSearchRecord(this.menuSearchRecord)
					}
				}
			} else {
				if (!this.menuSearchRecord.includes(value)) {
					this.menuSearchRecord.push(value)
					cache.setMenuSearchRecord(this.menuSearchRecord)
				}
			}
		},
		setButtons(val: any) {
			this.buttons = val;
			cache.setButtons(val);
		},
		setApplets(val: any) {
			this.applets = val;
			cache.setApplets(val);
		},
		setTabs(val: any) {
			this.tabs = val;
		},
		setAffixTabs(val: any) {
			if (this.affixTabs.length === 0) {
				this.affixTabs.push(...val);
				cache.setAffixTabs(this.affixTabs);
			}
		},
		changeAffixTabs (tab: any, isAffix: boolean) {
			if (isAffix) {
				// 固定tabs
				if (!this.affixTabs.some((o: any) => o.path === tab.path)) {
					const {path, name, meta} = tab;
					meta.affix = true;
					this.affixTabs.push({path, name, meta});
				}
			} else {
				// 取消固定tabs
				this.affixTabs = this.affixTabs.filter((o: any) => o.path !== tab.path);
			}
			cache.setAffixTabs(this.affixTabs);
		},
		setCacheRoutes(val: any) {
			this.cacheRoutes = val;
			cache.setKeepAliveRoutes(this.cacheRoutes);
		},
		clearToken() {
			if (this.remember) {
				cache.setUserInfo({username: this.user.username});
			} else {
				cache.deleteUserInfo();
			}
			cache.deleteToken();
			cache.deleteMenu();
			cache.deleteButtons();
			cache.deleteKeepAliveRoutes();
			location.reload();
		}
	
    }
})